const hostport='192.168.1.3:8866'
//const ws= new WebSocket('ws://192.168.1.3:8866/helloworld');;
//const ws=new WebSocket('ws://192.168.1.3:6066/videocall?Passport=aaa');
let ws=null;
let webRtcPeer;



// UI
let uiLocalVideo;
let uiRemoteVideo;
let uiState = null;
const UI_IDLE = 0;
const UI_STARTING = 1;
const UI_STARTED = 2;








window.onload = function()
{
    //console = new Console();
    console.log("Page loaded");
    uiLocalVideo = document.getElementById('uiLocalVideo');
    uiRemoteVideo = document.getElementById('uiRemoteVideo');
    uiSetState(UI_IDLE);

}

window.onbeforeunload = function()
{
    console.log("Page unload - Close WebSocket");
    if(ws){
        ws.close();
    }

}


function explainUserMediaError(err)
{
    const n = err.name;
    if (n === 'NotFoundError' || n === 'DevicesNotFoundError') {
        return "Missing webcam for required tracks";
    }
    else if (n === 'NotReadableError' || n === 'TrackStartError') {
        return "Webcam is already in use";
    }
    else if (n === 'OverconstrainedError' || n === 'ConstraintNotSatisfiedError') {
        return "Webcam doesn't provide required tracks";
    }
    else if (n === 'NotAllowedError' || n === 'PermissionDeniedError') {
        return "Webcam permission has been denied by the user";
    }
    else if (n === 'TypeError') {
        return "No media tracks have been requested";
    }
    else {
        return "Unknown error: " + err;
    }
}


function sendError(message)
{
    console.error(message);

    sendMessage({
        id: 'ERROR',
        message: message,
    });
}


function sendMessage(message)
{
    if (ws.readyState !== ws.OPEN) {
        console.warn("[sendMessage] Skip, WebSocket session isn't open");
        return;
    }

    const jsonMessage = JSON.stringify(message);
    console.log("[sendMessage] message: " + jsonMessage);
    ws.send(jsonMessage);
}


/* ============================= */
/* ==== WebSocket signaling ==== */
/* ============================= */




function handleProcessSdpAnswer(jsonMessage)
{
    console.log("[handleProcessSdpAnswer] SDP Answer from Kurento, process in WebRTC Peer");

    if (webRtcPeer == null) {
        console.warn("[handleProcessSdpAnswer] Skip, no WebRTC Peer");
        return;
    }
    //4。2绑定连接者对象到服务端  --流程结束
    webRtcPeer.processAnswer(jsonMessage.sdpAnswer, (err) => {
        if (err) {
            sendError("[handleProcessSdpAnswer] Error: " + err);
            stop();
            return;
        }

        console.log("[handleProcessSdpAnswer] SDP Answer ready; start remote video");
    startVideo(uiRemoteVideo);

    uiSetState(UI_STARTED);
});
}


// ADD_ICE_CANDIDATE -----------------------------------------------------------

function handleAddIceCandidate(jsonMessage)
{
    if (webRtcPeer == null) {
        console.warn("[handleAddIceCandidate] Skip, no WebRTC Peer");
        return;
    }

    webRtcPeer.addIceCandidate(jsonMessage.candidate, (err) => {
        if (err) {
            console.error("[handleAddIceCandidate] " + err);
            return;
        }
    });
}


// STOP ------------------------------------------------------------------------

function stop()
{
    if (uiState == UI_IDLE) {
        console.log("[stop] Skip, already stopped");
        return;
    }

    console.log("[stop]");

    if (webRtcPeer) {
        webRtcPeer.dispose();
        webRtcPeer = null;
    }

    uiSetState(UI_IDLE);
    hideSpinner(uiLocalVideo, uiRemoteVideo);

    sendMessage({
        id: 'STOP',
    });
}

function handleError(jsonMessage)
{
    const errMessage = jsonMessage.message;
    console.error("Kurento error: " + errMessage);

    console.log("Assume that the other side stops after an error...");
    stop();
}

/* ==================== */
/* ==== UI actions ==== */
/* ==================== */

// Start -----------------------------------------------------------------------
//第一步 新建本地连接
function uiStart()
{
    console.log("[start] Create WebRtcPeerSendrecv");
    uiSetState(UI_STARTING);
    showSpinner(uiLocalVideo, uiRemoteVideo);

    const options = {
            localVideo: uiLocalVideo,
            remoteVideo: uiRemoteVideo,
            mediaConstraints: { audio: true, video: true },
            onicecandidate: (candidate) => sendMessage({
            id: 'ADD_ICE_CANDIDATE',
            candidate: candidate,
        }),
        };

    webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
        function(err)
        {
            if (err) {
                sendError("[start/WebRtcPeerSendrecv] Error: "
                    + explainUserMediaError(err));
                stop();
                return;
            }

            console.log("[start/WebRtcPeerSendrecv] Created; start local video");
            //2。1将媒体信息显示到网页上
            startVideo(uiLocalVideo);

            console.log("[start/WebRtcPeerSendrecv] Generate SDP Offer");

            //第三步，生成消费者
            webRtcPeer.generateOffer((err, sdpOffer) => {
                if (err) {
                    sendError("[start/WebRtcPeerSendrecv/generateOffer] Error: " + err);
                    stop();
                    return;
                }

                sendMessage({
                                id: 'PROCESS_SDP_OFFER',
                                sdpOffer: sdpOffer,
                            });

            console.log("[start/WebRtcPeerSendrecv/generateOffer] Done!");
            uiSetState(UI_STARTED);
        });
        });
}


// Stop ------------------------------------------------------------------------

function uiStop()
{
    stop();
}



/* ================== */
/* ==== UI state ==== */
/* ================== */

function uiSetState(newState)
{
    switch (newState) {
        case UI_IDLE:
            uiEnableElement('#uiStartBtn', 'uiStart()');
            uiDisableElement('#uiStopBtn');
            break;
        case UI_STARTING:
            uiDisableElement('#uiStartBtn');
            uiDisableElement('#uiStopBtn');
            break;
        case UI_STARTED:
            uiDisableElement('#uiStartBtn');
            uiEnableElement('#uiStopBtn', 'uiStop()');
            break;
        default:
            console.warn("[setState] Skip, invalid state: " + newState);
            return;
    }
    uiState = newState;
}


function uiEnableElement(id, onclickHandler)
{
    $(id).attr('disabled', false);
    if (onclickHandler) {
        $(id).attr('onclick', onclickHandler);
    }
}


function uiDisableElement(id)
{
    $(id).attr('disabled', true);
    $(id).removeAttr('onclick');
}

function showSpinner()
{
    for (let i = 0; i < arguments.length; i++) {
        arguments[i].poster = './img/transparent-1px.png';
        arguments[i].style.background = "center transparent url('./img/spinner.gif') no-repeat";
    }
}


function hideSpinner()
{
    for (let i = 0; i < arguments.length; i++) {
        arguments[i].src = '';
        arguments[i].poster = './img/webrtc.png';
        arguments[i].style.background = '';
    }
}


function startVideo(video)
{
    // Manually start the <video> HTML element
    // This is used instead of the 'autoplay' attribute, because iOS Safari
    // requires a direct user interaction in order to play a video with audio.
    // Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video
    video.play().catch((err) => {
        if (err.name === 'NotAllowedError') {
    console.error("[start] Browser doesn't allow playing video: " + err);
}
else {
    console.error("[start] Error in video.play(): " + err);
}
});
}

function connectWs(){

   // this.ws=new WebSocket('ws://192.168.1.3:8866/helloworld');

    var username=$('#username').val();
    ws=new WebSocket('ws://192.168.1.3:6066/videocall?Passport='+username)
    ws.onopen = function(){
        //当WebSocket创建成功时，触发onopen事件
        console.log("open");
        //ws.send("hello"); //将消息发送到服务端
        //this.send('hello')
    }

    ws.onclose = function(e){
        //当客户端收到服务端发送的关闭连接请求时，触发onclose事件
        console.log("close");
    }
    ws.onerror = function(e){
        //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
        console.log(e);
    }

    ws.onmessage = function(message)
    {
        const jsonMessage = JSON.parse(message.data);
        console.log("[onmessage] Received message: " + message.data);

        switch (jsonMessage.id) {
            //第四步 回传并处理连接端信息
            case 'PROCESS_SDP_ANSWER':
                handleProcessSdpAnswer(jsonMessage);
                break;
            case 'ADD_ICE_CANDIDATE':
                handleAddIceCandidate(jsonMessage);
                break;
            case 'ERROR':
                handleError(jsonMessage);
                break;
            default:
                // Ignore the message
                console.warn("[onmessage] Invalid message, id: " + jsonMessage.id);
                break;
        }
    }



    console.log(username);

}


